#!/bin/bash
function install_jenkins() {
    echo "安装Jenkins" >>$logs_file
    rm -rf /tmp/.jenkins.err.info
    jenkinsoPid=`ps aux|grep jenkins.war|grep java|grep -v grep|awk '{print $2}'`
    if [ -n "$jenkinsoPid" ];then
        whiptail --backtitle "Author: Elvis" --title "警告" --msgbox "系统已经存在正在运行的Jenkins请停止并卸载后继续！" 10 60
        sleep 0.10
        return 1
    fi
    whiptail --backtitle "Author: Elvis" --title "提示" --yesno \
"安装Jenkins前，请确认已安装JDK，Jenkins与JDK对应关系如下\n\
* 2.164及后续版本：Java 8 或者Java 11\n\
* 2.54及后续版本:  Java 8\n\
* 1.612及后续版本: Java 7\n
是否继续安装？" 12 60
    if [ "$?" != "0" ];then
        sleep 0.15
        return 1
    fi
    
    jenkinsVer=
    jenkins_dot=
    jenkins_digit=
    jenkins_endwith=
    while [[ ! $jenkins_digit =~ ^[1-9][0-9]+$ || "$jenkins_dot" == "0" || "$jenkins_endwith" == "." ]]
    do
        jenkinsVer=$(whiptail --backtitle "Author: Elvis" --title "版本选择" --radiolist --nocancel \
        "请选择要安装的Jenkins版本？" 12 60 3 \
        "2.46.3" "需要JAVA 7                 " ON \
        "2.222.3" "需要JAVA 8" OFF \
        "Other"  "自定义版本" OFF 3>&1 1>&2 2>&3)
        
        if [ "$jenkinsVer" == "Other" ];then
            jenkinsVer=$(whiptail --backtitle "Author: Elvis" --title "Jenkins版本" --inputbox --nocancel \
                        "请输入要安装的Jenkins版本，格式为X.XXX.X" 10 60 3>&1 1>&2 2>&3)
        fi
        
        jenkinsVer=`echo $jenkinsVer`
        jenkins_dot=$(echo $jenkinsVer|grep -o "\."|wc -l)
        jenkins_digit=$(echo $jenkinsVer|sed 's/\.//g')
        jenkins_endwith=${jenkinsVer:0-1}
        if [[ ! $jenkins_digit =~ ^[1-9][0-9]+$ || "$jenkins_dot" == "0" || $jenkins_dot -gt 2 || "$jenkins_endwith" == "." ]];then
            whiptail --backtitle "Author: Elvis" --title "错误" --msgbox "jenkins版本号由.结尾的数字和.组成，且不以.结尾，请重新选择或输入！" 10 60
            sleep 0.5
        fi  
    done
    jenkinsVer=`echo $jenkinsVer`
    jenkinsPack="jenkins-$jenkinsVer-1.1.noarch.rpm"
    
    
    jenkinsPath=$(whiptail --backtitle "Author: Elvis" --title "Jenkins配置" --inputbox --nocancel \
    "请输入Jenkins HOME目录，用于存放Jenkins配置及数据" 10 60 "/var/lib/jenkins" 3>&1 1>&2 2>&3)
    jenkinsPath=${jenkinsPath:-/var/lib/jenkins}
    jenkinsPath=`echo $jenkinsPath`
    jenkinsPath=${jenkinsPath%/}
    isNull=`ls $jenkinsPath/* 2>/dev/null | wc -l`
    if [[ $isNull -gt 0 ]];then
        whiptail --backtitle "Author: Elvis" --title "警告" --yes-button "继续" --no-button "退出" --yesno "给出的Jenkins_HOME目录非空，继续安装会删除已有数据！\n\n是否继续安装？" 10 60
        if [ "$?" != "0" ];then
         sleep 0.10
         return 1
        fi
    fi
    
    command -v ss >/dev/null 2>&1
    if [ "$?" == "0" ];then
        listen_cmd="ss -lnpt"
    else
        command -v netstat >/dev/null 2>&1
        if [ "$?" == "0" ];then
          listen_cmd="netstat -tnlp"
        fi
    fi
    [[ $listen_cmd ]] && PortCheck=Yes || PortCheck=No
    PortUsed=
    PortUsed_Pro=
    jenkinsPort=
    while [[ ! "$jenkinsPort" =~ ^[1-9][0-9]+$ || "$PortUsed" == "Yes" ]]
    do
        jenkinsPort=$(whiptail --backtitle "Author: Elvis" --title "Jenkins配置" --inputbox --nocancel \
        "请输入Jenkins监听端口，注意端口是否被占用" 10 60 "8080" 3>&1 1>&2 2>&3)
        if [[ ! "$jenkinsPort" =~ ^[1-9][0-9]+$ ]];then
             whiptail --backtitle "Author: Elvis" --title "错误" --msgbox "jenkins端口只能为两位及以上的且不以0开头的数字组成，请重新输入！" 10 60
             sleep 0.5
        else
            if [ "$PortCheck" == "Yes" ];then
                PortUsed_Pro=`$listen_cmd 2>/dev/null |grep ":${jenkinsPort} "`
                if [ -n "$PortUsed_Pro" ];then
                  PortUsed=Yes
                  whiptail --backtitle "Author: Elvis" --title "错误" --msgbox "Jenkins监听端口已被使用，请重新输入！" 8 60
                else
                  PortUsed=No
                fi
            else
                PortUsed=No
            fi
        fi
    done
    jenkinsPort=${jenkinsPort:-8080}
    jenkinsPort=`echo $jenkinsPort`

    source /etc/profile >/dev/null 2>&1
    source ~/.bash_profile >/dev/null 2>&1
    source ~/.bashrc >/dev/null 2>&1
    javaPath=`command -v java`
    if [ -z "$javaPath" ];then
        javaPath=$(whiptail --backtitle "Author: Elvis" --title "JDK配置" --inputbox --nocancel \
    "系统未找到到java命令，请手动输入java命令路径" 10 60 "/usr/bin/java" 3>&1 1>&2 2>&3)
    else
        whiptail --backtitle "Author: Elvis" --title "警告" --yes-button "确定" --no-button "修改" --yesno "系统检测到java命令路径为$javaPath\n\n如果正确请确认，不正确请修改." 10 60
        if [ "$?" != "0" ];then
          javaPath=$(whiptail --backtitle "Author: Elvis" --title "JDK配置" --inputbox --nocancel "请输入java命令位置" 10 60 "/usr/bin/java" 3>&1 1>&2 2>&3)
        fi
    fi
    javaPath=`echo $javaPath`
    javaOut=`$javaPath -version 2>&1|grep 'version "'`
    if [ -z "$javaOut" ];then
        msg="设置的java命令路径错误，执行java -version命令错误，退出jenkins安装"
        echo "`date "+%Y-%m-%d %H:%M:%S"` $msg" >>$logs_file
        whiptail --backtitle "Author: Elvis" --title "错误" --msgbox "$msg" 10 70
        sleep 0.10
        return 1
    else
        java_main_version=`$javaPath -version 2>&1|grep 'version "'|awk -F"." '{print $2}'`
        jenkinsVer_main=${jenkinsVer%.*}
        if [ "${#jenkinsVer_main}" == "3" ];then
          jenkinsVer_1=${jenkinsVer_main//./00}
        elif [ "${#jenkinsVer_main}" == "4" ];then
          jenkinsVer_1=${jenkinsVer_main//./0}
        else
          jenkinsVer_1=${jenkinsVer_main//./}
        fi

        if [[ $jenkinsVer_1 -ge 2054 && $java_main_version -lt 8 ]];then
          whiptail --backtitle "Author: Elvis" --title "警告" --yesno "要安装的Jenkins版本需要JDK8及以上版本,若继续，\n安装完成Jenkins后，Jenkins将无法正常工作！！" 10 60
          if [ "$?" != "0" ];then
             sleep 0.10
             return 1
          fi
        fi
        if [[ $jenkinsVer_1 -lt 2054 && $jenkinsVer_1 -ge 1612 && $java_main_version -lt 7 ]];then
          whiptail --backtitle "Author: Elvis" --title "警告" --yesno "要安装的Jenkins版本需要JDK7版本，若继续，\n安装完成Jenkins后，Jenkins将无法正常工作！！" 10 60
          if [ "$?" != "0" ];then
             sleep 0.10
             return 1
          fi
        fi
    fi
    # java版本信息
    java_version=$($javaPath -version 2>&1|head -n 1)
    
    whiptail --backtitle "Author: Elvis" --title "Jenkins安装信息汇总" --yesno "\nJenkins版本：$jenkinsVer\nJenkins路径：$jenkinsPath\nJenkins端口：$jenkinsPort\nJAVA命令：$javaPath\nJDK版本信息：$java_version\n\nYes以继续安装，No退出Jenkins安装" 15 70
    if [ "$?" != "0" ];then
        sleep 0.10
        return 1
    fi

    jenkinsHome="$workHome/packages/jenkins"
    {
    echo 1
    if [ "$die_network" == "true" ];then
        ping -c 2 -w 5 180.76.76.76 >/dev/null 2>&1
        if [ "$?" != "0" ];then
           die_network="true"
        else
           die_network="false"
        fi
    else
        sleep 1
    fi
    cd $jenkinsHome
    
    if [[ ! -f $jenkinsHome/$jenkinsPack && "$die_network" == "false" ]];then
        msg="下载jenkins安装包"
        echo "`date "+%Y-%m-%d %H:%M:%S"` $msg" >>$logs_file
        echo -e "XXX\n30\n$msg\nXXX"
        echo 30
        if [ $jenkins_dot -eq 2 ];then
          iSstable="redhat-stable"
        else
          iSstable="redhat"
        fi
        
        echo "从华为云下载jenkins" >>$logs_file
        curl -O --fail https://mirrors.huaweicloud.com/jenkins/$iSstable/$jenkinsPack >>$logs_file 2>&1
        if [ "$?" != "0" ];then
          echo "从官网下载jenkins" >>$logs_file 
          curl -O --fail http://archives.jenkins-ci.org/$iSstable/$jenkinsPack >>$logs_file 2>&1
        fi
        if [ "$?" != "0" ];then
          echo "从清华大学镜像站下载jenkins" >>$logs_file 
          curl -O --fail https://mirrors.tuna.tsinghua.edu.cn/jenkins/$iSstable/$jenkinsPack >>$logs_file 2>&1
        fi
        if [ "$?" != "0" ];then
          msg="下载安装包失败，请检查网络或者是否存在此版本的Jenkins"
          echo "$msg" >/tmp/.jenkins.err.info
          echo -e "XXX\n35\n$msg\nXXX"
          echo 35
          sleep 3
          return 1
        fi
    elif [[ ! -f $jenkinsHome/$jenkinsPack && "$die_network" == "true" ]];then
        msg="你的主机未联网，请提前手动下载安装包，使用离线安装！！！"
        echo "$msg" >/tmp/.jenkins.err.info
        echo "`date "+%Y-%m-%d %H:%M:%S"` $msg" >>$logs_file
        echo -e "XXX\n35\n$msg\nXXX"
        echo 35
        sleep 3
        return 1
    fi
    
    msg="卸载之前安装的Jenkins"
    echo "`date "+%Y-%m-%d %H:%M:%S"` $msg" >>$logs_file
    echo -e "XXX\n50\n$msg\nXXX"
    echo 50
    yum -y remove jenkins >>$logs_file 2>&1
    rm -rf /var/log/jenkins
    rm -rf /usr/lib/jenkins
    rm -rf /var/cache/jenkins
    rm -rf $jenkinsPath
    
    msg="安装Jenkins依赖软件"
    echo "`date "+%Y-%m-%d %H:%M:%S"` $msg" >>$logs_file
    echo -e "XXX\n55\n$msg\nXXX"
    yum -y install epel-release >>$logs_file 2>&1
    yum -y install fontconfig daemonize >>$logs_file 2>&1
    
    msg="开始安装Jenkins"
    echo "`date "+%Y-%m-%d %H:%M:%S"` $msg" >>$logs_file
    echo -e "XXX\n60\n$msg\nXXX"
    echo 60
    rpm -ivh $jenkinsPack >>$logs_file 2>&1
    if [ "$?" != "0" ];then
        msg="安装失败，检查RPM包是否完整！"
        echo "`date "+%Y-%m-%d %H:%M:%S"` $msg" >>$logs_file
        echo -e "XXX\n65\n$msg\nXXX"
        echo "$msg" >/tmp/.jenkins.err.info
        echo 60
        sleep 3
        return 1
    fi
    isNull_d=`ls /var/lib/jenkins/* 2>/dev/null | wc -l`
    if [[ $isNull_d -eq 0 ]];then
        rm -rf /var/lib/jenkins/
    fi
    mkdir -p $jenkinsPath >/dev/null 2>&1
    chown -R jenkins:jenkins $jenkinsPath >/dev/null 2>&1
    
    msg="修改Jenkins配置"
    echo "`date "+%Y-%m-%d %H:%M:%S"` $msg" >>$logs_file
    echo -e "XXX\n80\n$msg\nXXX"
    echo 80
    sleep 1
    sed -i "s#^JENKINS_JAVA_CMD=.*#JENKINS_JAVA_CMD=\"$javaPath\"#g" /etc/sysconfig/jenkins >>$logs_file 2>&1
    sed -i 's/JENKINS_AJP_PORT=.*/JENKINS_AJP_PORT="-1"/g' /etc/sysconfig/jenkins >>$logs_file 2>&1
    sed -i "s#^JENKINS_HOME=.*#JENKINS_HOME=\"$jenkinsPath\"#g" /etc/sysconfig/jenkins >>$logs_file 2>&1
    sed -i "s#^JENKINS_PORT=.*#JENKINS_PORT=\"$jenkinsPort\"#g" /etc/sysconfig/jenkins >>$logs_file 2>&1
  
    msg="启动Jenkins"
    echo "`date "+%Y-%m-%d %H:%M:%S"` $msg" >>$logs_file
    echo -e "XXX\n85\n$msg\nXXX"
    echo 85
    service jenkins restart >/dev/null 2>>$logs_file
    echo -e "XXX\n86\n等待Jenkins启动中.....\nXXX"
    echo 86
    n=1
    response_status=1
    updateCenter_update=No
    while [ ! -f $jenkinsPath/secrets/initialAdminPassword -o $response_status -ne 200 ]
    do
        msg="等待jenkins启动 $n/360 s"
        echo "`date "+%Y-%m-%d %H:%M:%S"` $msg" >>$logs_file
        echo -e "XXX\n88\n$msg\nXXX"
        echo 88
        let n+=1
        sleep 1
        if [ $n -gt 360 ];then
           break
        fi
        response_status=$(curl -I -m 10 -o /dev/null -s -w %{http_code} http://127.0.0.1:${jenkinsPort}/login)
        if [ -f $jenkinsPath/hudson.model.UpdateCenter.xml -a "${updateCenter_update}" == "No" ];then
            updateCenter="https://mirrors.tuna.tsinghua.edu.cn/jenkins/updates/update-center.json"
            #updateCenter="https://repo.huaweicloud.com/jenkins/updates/update-center.json"
            sed -i "s#http.*://.*update-center.json#$updateCenter#g" $jenkinsPath/hudson.model.UpdateCenter.xml >>$logs_file 2>&1
            updateCenter_update=Yes
        fi
    done
    
    if [ $response_status -eq 200 ];then
        msg="Jenkins启动成功"
    else
        msg="启动Jenkins超时"
    fi
    echo "`date "+%Y-%m-%d %H:%M:%S"` $msg" >>$logs_file
    echo -e "XXX\n89\n$msg\nXXX"
    echo 89
    sleep 2
    
    msg="启用Jenkins插件安装镜像加速"
    echo "`date "+%Y-%m-%d %H:%M:%S"` $msg" >>$logs_file
    echo -e "XXX\n90\n$msg\nXXX"
    echo 90
    sleep 1
    
    if [ -f $jenkinsPath/updates/default.json ];then
        offical_url=$(cat $jenkinsPath/updates/default.json |sed 's#,"url":"#\n#g'|egrep -o \
        "https://updates\..*?/download/.*?\.hpi"|awk -F'/plugins' '{print $1}'|sort -u|head -n1)
        mirrors_url="https://mirrors.tuna.tsinghua.edu.cn/jenkins"
        #mirrors_url="https://repo.huaweicloud.com/jenkins"
        sed -i "s#${offical_url}#${mirrors_url}#g" $jenkinsPath/updates/default.json >>$logs_file 2>&1
        sed -i 's#http://www.google.com#https://www.baidu.com#g' $jenkinsPath/updates/default.json >>$logs_file 2>&1
        # sed -i 's#http://updates.jenkins-ci.org/download#https://mirrors.tuna.tsinghua.edu.cn/jenkins#g' $jenkinsPath/updates/default.json
        # sed -i 's#https://updates.jenkins.io/download#https://mirrors.tuna.tsinghua.edu.cn/jenkins#g' $jenkinsPath/updates/default.json
        msg="重启Jenkins以使配置生效"
        echo "`date "+%Y-%m-%d %H:%M:%S"` $msg" >>$logs_file
        echo -e "XXX\n91\n$msg\nXXX"
        echo 91
        service jenkins restart >/dev/null 2>>$logs_file
        msg="等待Jenkins重新启动中....."
        echo "`date "+%Y-%m-%d %H:%M:%S"` $msg" >>$logs_file
        echo -e "XXX\n92\n$msg\nXXX"
        echo 92
        n=1
        response_status=1
        while [ $response_status -ne 200 ]
        do
            msg="等待Jenkins配置生效 $n/360 s"
            echo "`date "+%Y-%m-%d %H:%M:%S"` $msg" >>$logs_file
            echo -e "XXX\n93\n$msg\nXXX"
            echo 93
            let n+=1
            sleep 1
            if [ $n -gt 360 ];then
                break
            fi
            response_status=$(curl -I -m 10 -o /dev/null -s -w %{http_code} http://127.0.0.1:${jenkinsPort}/login)
        done
        msg="若重新获取了插件更新信息，则应参考说明以重新启用镜像加速"
    else
        msg="未生成default.json文件，请参考说明以启用镜像加速"
    fi
    echo "`date "+%Y-%m-%d %H:%M:%S"` $msg" >>$logs_file
    echo -e "XXX\n94\n$msg\nXXX"
    echo 94
    sleep 2

    if [ -f $jenkinsHome/jenkins-plugins-$jenkinsVer.zip ];then
        msg="加载Jenkins插件"
        echo "`date "+%Y-%m-%d %H:%M:%S"` $msg" >>$logs_file
        echo -e "XXX\n95\n$msg\nXXX"
        echo 95
        rm -rf $jenkinsHome/jenkins-plugins
        mkdir $jenkinsHome/jenkins-plugins
        /bin/cp -f $jenkinsHome/jenkins-plugins-$jenkinsVer.zip $jenkinsHome/jenkins-plugins >/dev/null 2>&1
        cd $jenkinsHome/jenkins-plugins
        unzip jenkins-plugins-$jenkinsVer.zip >/dev/null 2>>$logs_file
        #停止jenkins
        service jenkins stop  >/dev/null 2>>$logs_file
        find . -name "*.jpi" -type f -exec /bin/mv -f {} $jenkinsPath/plugins/ \; >/dev/null 2>&1
        find . -name "*.hpi" -type f -exec /bin/mv -f {} $jenkinsPath/plugins/ \; >/dev/null 2>&1
        cd $jenkinsHome
        rm -rf jenkins-plugins
        msg="重新启动Jenkins"
        echo "`date "+%Y-%m-%d %H:%M:%S"` $msg" >>$logs_file
        echo -e "XXX\n97\n$msg\nXXX"
        echo 97
        service jenkins restart >/dev/null 2>>$logs_file
        echo -e "XXX\n99\n等待Jenkins重启中.....\nXXX"
        echo 99
        i=1
        while [ -f $jenkinsPath/queue.xml ]
        do
           echo "等待jenkins重启 $i" >>$logs_file
           let i+=1
           sleep 1
           if [ $i -gt 20 ];then
               jenkinsPidr=`ps aux|grep jenkins.war|grep java|grep -v grep|awk '{print $2}'`
               [[ -z "$jenkinsPidr" ]] && break
           fi        
           if [ $i -gt 50 ];then
                break
           fi
        done
    fi
    echo -e "XXX\n100\ndone！！！\nXXX"
    echo 100
    sleep 1 
    } | whiptail --backtitle "Author: Elvis" --title "安装Jenkins" --gauge " " 6 60 0
    if [ -f /tmp/.jenkins.err.info ];then
        errinfo=`cat /tmp/.jenkins.err.info` >>$logs_file
        rm -rf /tmp/.jenkins.err.info
        whiptail --backtitle "Author: Elvis" --title "错误" --msgbox "Jenkins安装失败！\n$errinfo" 10 70
        sleep 0.10
        return 1
    fi
    #判断是否启动
    if [ ! -f $jenkinsPath/secrets/initialAdminPassword ];then
        passwd_tip="初始密码位于：$jenkinsPath/secrets/initialAdminPassword"
    else
        jenkins_init_pw=`cat $jenkinsPath/secrets/initialAdminPassword 2>>$logs_file`
        passwd_tip="初始密码为：$jenkins_init_pw"
    fi
    jenkinsPid=`ps aux|grep jenkins.war|grep java|grep -v grep|awk '{print $2}'`
    if [ -n "$jenkinsPid" ];then
        echo "Jenkins $jenkinsVer安装成功" >>$logs_file
        whiptail --backtitle "Author: Elvis" --title "消息" --msgbox "Jenkins $jenkinsVer安装成功！！！\n\
访问地址：http://$ipaddr:$jenkinsPort\n${passwd_tip}\n数据文件位置：$jenkinsPath\n日志文件：/var/log/jenkins" 13 80
    else
        echo "Jenkins安装失败" >>$logs_file
        whiptail --backtitle "Author: Elvis" --title "错误" --msgbox "Jenkins $jenkinsVer安装失败！！！\n请使用service jenkins status以及日志文件排查错误." 10 70
    fi
    sleep 0.10 
}